import Axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index'
import useUser from '@/store/user'
// import { SynchStatus } from './config'
// import useCommon from '@/store/common'

Axios.defaults.timeout = 120000
Axios.defaults.headers
//返回其他状态吗
Axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500 // 默认的
}
//跨域请求，允许保存cookie0
Axios.defaults.withCredentials = true


//请求拦截
Axios.interceptors.request.use((config) => {
  //配置token
  if (config.headers) {
    config.headers['Authorization'] = 'Bearer ' + useUser.setup().store.token as string
  }
  // 内外网环境
  // const {situation} = useCommon.setup().store.$state
  // 外网环境未同步，内网环境已同步
  // config.params = {...config.params} // 统一配置同步状态：0未同步/1已同步(离线使用)
  return config
}, (error) => {
  //TODO请求错误
  return Promise.reject(error)
})

const ErrorHTTPCodes = [401, 403, 404, 408, 409, 500, 501, 502, 503, 504, 505]
//响应拦截
Axios.interceptors.response.use((res) => {
  const index = ErrorHTTPCodes.indexOf(res.status)
  if (index === -1) {
    const status = res.data.code || 2000
    const message = res.data.msg || '未知错误'
    const {success} = res.data
    //如果TOKEN过期 进行路由跳转
    if (status === 401) {
      ElMessage({
        message:'登录凭证过期,请重新重录'
      })
      router.push({name:'Login'})
    }
    //其他错误飘字
    if (status !== 2000 || success === false) {
      ElMessage({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(status))
    } else {
      return res
    }
  } else {
    ElMessage({
      message: 'HTTP' + res.status,
      type: 'error'
    })
    return Promise.reject(new Error('HTTP' + res.status))
  }
}, (error) => {
  return Promise.reject(error)
})
export default Axios